<template>
  <view class="phones">
    <view class="phones_top">
      <text>{{ realname ? '更换姓名' : '添加姓名' }}</text>
    </view>
    <view class="phones_tel">
      <text style="letter-spacing: 10px">姓名</text>
      <input type="text" :placeholder="realname ? realname : '请输入姓名'" maxlength="11" v-model="name" style="width: 80%"
        @input="fpNumInput" />
    </view>
    <view class="phone_bottom">
      <text @click="close()">取消</text>
      <text @click="submit()">确定</text>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { getDriverID } from '@/stores/driverID';
  import { useUserStore } from '@/stores/user';
  import { showLoading, showToast, successToast } from '@/utils/prompt';
  import { toPublish } from '@mqtt';
  import { nextTick, ref } from 'vue';

  const userInfo = useUserStore();
  const realname = userInfo.realname;
  const driver_id = getDriverID();
  //view
  const name = ref('');
  const repeat = ref(true); //放重复点击
  /**
   * 正则输入的数据
   */
  function fpNumInput(e : any) {
    const o = e.detail;
    const inputRule = /[^\u4E00-\u9FA5]/g; ///只能输入中文
    nextTick(function () {
      name.value = o.value.replace(inputRule, '');
    });
  }
  const emits = defineEmits(['close']);
  function close() {
    emits('close');
  }
  function submit() {
    const Mename = name.value ? name.value : realname;
    if (!Mename) {
      showToast('请填完整的信息');
      return;
    }
    const payload = {
      driver_id,
      name: Mename,
    };
    showLoading('正在提交');
    if (!repeat.value) {
      return
    }
    repeat.value = false
    toPublish('driver/editDriverName', payload, (obj : any) => {
      if (obj.code === 1) {
        repeat.value = true
        userInfo.getUserInfo();
        successToast(obj.msg);
        emits('close');
      } else {
        repeat.value = true
        showToast(obj.msg);
      }
    });
  }
</script>
<style scoped lang="less">
  @import url('../mine/less/mine_name.less');
</style>